package cn.com.homeyoda.aimate.aihealth.ui.health.viewModel;

import android.app.Application;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.wzq.mvvmsmart.binding.command.BindingAction;
import com.wzq.mvvmsmart.binding.command.BindingCommand;
import com.wzq.mvvmsmart.event.StateLiveData;
import com.wzq.mvvmsmart.utils.KLog;
import com.wzq.mvvmsmart.utils.RxUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import cn.com.homeyoda.aimate.aihealth.base.BaseViewModel;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.JoinPlanBody;
import cn.com.homeyoda.aimate.aihealth.bean.MyselfPlanBean;
import cn.com.homeyoda.aimate.aihealth.bean.SportPlanBean;
import cn.com.homeyoda.aimate.aihealth.bean.SportPlanTitleBean;
import cn.com.homeyoda.aimate.aihealth.bean.UnJoinPlanBody;
import cn.com.homeyoda.aimate.aihealth.bean.WeekBean;
import cn.com.homeyoda.aimate.aihealth.data.Repository;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import cn.com.homeyoda.aimate.aihealth.ui.health_manage.HealthManageViewModel;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created By liuxinhua
 * Created Time 2025/2/27
 */
public class SportPlanViewModel extends BaseViewModel<Repository> {

    public StateLiveData<FamilyMembersBean.DataBean.FamilyMembers> planUserStateLiveData;
    public StateLiveData<List<SportPlanTitleBean.DataBean>> planTitleStateLiveData;
    public StateLiveData<List<SportPlanBean.RowsBean>> planStateLiveData;
    public StateLiveData<String> joinPlanStateLiveData;
    public StateLiveData<MyselfPlanBean.DataBean> planDetailsLiveData;
    public StateLiveData<MyselfPlanBean> myselfPlanBeanStateLiveData;


    public ArrayList<FamilyMembersBean.DataBean.FamilyMembers> familyMembers;
    public StateLiveData<List<WeekBean>> weekList;
    public StateLiveData<Integer> mWeek;


    public SportPlanViewModel(@NonNull Application application, Repository model) {
        super(application, model);
        planUserStateLiveData = new StateLiveData<>();
        planTitleStateLiveData = new StateLiveData<>();
        planStateLiveData = new StateLiveData<>();
        planDetailsLiveData = new StateLiveData<>();
        joinPlanStateLiveData = new StateLiveData<>();
        myselfPlanBeanStateLiveData = new StateLiveData<>();

        weekList = new StateLiveData<>();
        mWeek = new StateLiveData<>();
        familyMembers = new ArrayList<>();
    }


    /**
     * 初始化用户信息
     */
    public void initUserInfo() {
        if (TextUtils.isEmpty(model.getUserId())) {
            Log.d(TAG, "initUserInfo error : not login !");
            return;
        }


        model.getFamilyMembers(model.getFamilyId())
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<FamilyMembersBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        planUserStateLiveData.setLoading();
                    }

                    @Override
                    public void onNext(FamilyMembersBean response) {
                        if (response.getCode() == 200) {
                            familyMembers = response.getData().getFamilyMembers();
                            if (familyMembers.size() > 0) {
                                for (FamilyMembersBean.DataBean.FamilyMembers userMember : familyMembers) {
                                    if (model.getUserId().equals(String.valueOf(userMember.getUserId()))) {
                                        planUserStateLiveData.setValueAndSuccess(userMember);
                                    }
                                }

                                if (planUserStateLiveData.getValue() == null) {
                                    planUserStateLiveData.setValueAndSuccess(familyMembers.get(0));
                                }
                            } else {
                                planUserStateLiveData.setError();
                            }

                        } else {
                            planUserStateLiveData.setError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        planUserStateLiveData.setError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                        planUserStateLiveData.setIdle();
                    }
                });


    }

    /**
     * 初始化运动计划标题列表
     */
    public void initPlanInfo() {
        model.sportPlanTypes()
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<SportPlanTitleBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        planTitleStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(SportPlanTitleBean sportPlanTitleBean) {
                        if (sportPlanTitleBean.getCode() == 200) {
                            List<SportPlanTitleBean.DataBean> titles = sportPlanTitleBean.getData();
                            titles.add(0, new SportPlanTitleBean.DataBean("全部计划", ""));
                            planTitleStateLiveData.postValueAndSuccess(titles);
                            querySportPlans(titles.get(0).getTypeValue());
                        } else {
                            planTitleStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        planTitleStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        planTitleStateLiveData.postIdle();
                    }
                });

    }

    /**
     * 查询运动计划详情
     *
     * @param faceId
     * @param planId
     * @param date
     */
    public void initPlanDetails(String faceId, String planId, String date) {
        model.queryMyselfPlan(faceId, planId, date)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<MyselfPlanBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        planDetailsLiveData.postLoading();
                    }

                    @Override
                    public void onNext(MyselfPlanBean myselfPlanBean) {
                        if (myselfPlanBean.getCode() == 200 && myselfPlanBean.getData() != null) {
                            planDetailsLiveData.postValueAndSuccess(myselfPlanBean.getData());
                        } else {
                            planDetailsLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        planDetailsLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        planDetailsLiveData.postIdle();
                    }
                });
    }

    public void initWeek() {
        getCurrentWeekDates();
    }

    public void selectNewWeek(Calendar calendar) {
        List<WeekBean> weekBeanList = new ArrayList<>();
        int mWeekPosition = 0;

        // 设置每周的第一天为周一（默认周日为第一天）
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 获取当前是本周的第几天（周日=1，周一=2...）
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        switch (dayOfWeek) {
            case Calendar.SUNDAY:
                //"周日"
                mWeekPosition = 6;
                break;
            case Calendar.MONDAY:
                //"周一"
                mWeekPosition = 0;
                break;
            case Calendar.TUESDAY:
                mWeekPosition = 1;
                break;
            case Calendar.WEDNESDAY:
                mWeekPosition = 2;
                break;
            case Calendar.THURSDAY:
                mWeekPosition = 3;
                break;
            case Calendar.FRIDAY:
                mWeekPosition = 4;
                break;
            case Calendar.SATURDAY:
                mWeekPosition = 5;
                break;
            default:
                mWeekPosition = 0;
        }


        // 计算与本周第一天的偏移量
        int daysSinceMonday;
        if (calendar.getFirstDayOfWeek() == Calendar.MONDAY) {
            daysSinceMonday = dayOfWeek - Calendar.MONDAY;
            if (daysSinceMonday < 0) {
                daysSinceMonday += 7;
            }
        } else {
            daysSinceMonday = dayOfWeek - Calendar.SUNDAY;
            if (dayOfWeek == Calendar.SUNDAY) {
                daysSinceMonday = 6;
            } else {
                daysSinceMonday -= 1;
            }
        }

        calendar.add(Calendar.DAY_OF_YEAR, -daysSinceMonday);

        SimpleDateFormat dateFormat = null;
        SimpleDateFormat dayFormat = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            dayFormat = new SimpleDateFormat("dd", Locale.getDefault());
            // 打印本周七天日期
            for (int i = 0; i < 7; i++) {
                String dateStr = dateFormat.format(calendar.getTime());
                String dayStr = dayFormat.format(calendar.getTime());
                switch (i) {
                    case 0:
                        weekBeanList.add(new WeekBean("周一", dateStr, dayStr));
                        break;
                    case 1:
                        weekBeanList.add(new WeekBean("周二", dateStr, dayStr));
                        break;
                    case 2:
                        weekBeanList.add(new WeekBean("周三", dateStr, dayStr));
                        break;
                    case 3:
                        weekBeanList.add(new WeekBean("周四", dateStr, dayStr));
                        break;
                    case 4:
                        weekBeanList.add(new WeekBean("周五", dateStr, dayStr));
                        break;
                    case 5:
                        weekBeanList.add(new WeekBean("周六", dateStr, dayStr));
                        break;
                    case 6:
                        weekBeanList.add(new WeekBean("周日", dateStr, dayStr));
                        break;
                }

                weekList.setValue(weekBeanList);

                mWeek.setValue(mWeekPosition);

                calendar.add(Calendar.DAY_OF_YEAR, 1);
            }
        }
    }


    private void getCurrentWeekDates() {
        List<WeekBean> weekBeanList = new ArrayList<>();
        int mWeekPosition = 0;

        Calendar calendar = Calendar.getInstance();
        // 设置每周的第一天为周一（默认周日为第一天）
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 获取当前是本周的第几天（周日=1，周一=2...）
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        switch (dayOfWeek) {
            case Calendar.SUNDAY:
                //"周日"
                mWeekPosition = 6;
                break;
            case Calendar.MONDAY:
                //"周一"
                mWeekPosition = 0;
                break;
            case Calendar.TUESDAY:
                mWeekPosition = 1;
                break;
            case Calendar.WEDNESDAY:
                mWeekPosition = 2;
                break;
            case Calendar.THURSDAY:
                mWeekPosition = 3;
                break;
            case Calendar.FRIDAY:
                mWeekPosition = 4;
                break;
            case Calendar.SATURDAY:
                mWeekPosition = 5;
                break;
            default:
                mWeekPosition = 0;
        }


        // 计算与本周第一天的偏移量
        int daysSinceMonday;
        if (calendar.getFirstDayOfWeek() == Calendar.MONDAY) {
            daysSinceMonday = dayOfWeek - Calendar.MONDAY;
            if (daysSinceMonday < 0) {
                daysSinceMonday += 7;
            }
        } else {
            daysSinceMonday = dayOfWeek - Calendar.SUNDAY;
            if (dayOfWeek == Calendar.SUNDAY) {
                daysSinceMonday = 6;
            } else {
                daysSinceMonday -= 1;
            }
        }

        calendar.add(Calendar.DAY_OF_YEAR, -daysSinceMonday);

        SimpleDateFormat dateFormat = null;
        SimpleDateFormat dayFormat = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            dayFormat = new SimpleDateFormat("dd", Locale.getDefault());
            // 打印本周七天日期
            for (int i = 0; i < 7; i++) {
                String dateStr = dateFormat.format(calendar.getTime());
                String dayStr = dayFormat.format(calendar.getTime());
                switch (i) {
                    case 0:
                        weekBeanList.add(new WeekBean("周一", dateStr, dayStr));
                        break;
                    case 1:
                        weekBeanList.add(new WeekBean("周二", dateStr, dayStr));
                        break;
                    case 2:
                        weekBeanList.add(new WeekBean("周三", dateStr, dayStr));
                        break;
                    case 3:
                        weekBeanList.add(new WeekBean("周四", dateStr, dayStr));
                        break;
                    case 4:
                        weekBeanList.add(new WeekBean("周五", dateStr, dayStr));
                        break;
                    case 5:
                        weekBeanList.add(new WeekBean("周六", dateStr, dayStr));
                        break;
                    case 6:
                        weekBeanList.add(new WeekBean("周日", dateStr, dayStr));
                        break;
                }


                weekList.setValue(weekBeanList);

                mWeek.setValue(mWeekPosition);

                calendar.add(Calendar.DAY_OF_YEAR, 1);
            }
        }


    }


    /**
     * 查询运动计划列表
     *
     * @param planType
     */
    public void querySportPlans(String planType) {
        model.querySportPlans(planType)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<SportPlanBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        planStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(SportPlanBean sportPlanBean) {
                        if (sportPlanBean.getCode() == 200) {
                            planStateLiveData.postValueAndSuccess(sportPlanBean.getRows());
                        } else {
                            planStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        planStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        planStateLiveData.postIdle();
                    }
                });
    }

    /**
     * 加入计划
     *
     * @param faceId
     * @param planId
     * @param date
     * @param plan
     */
    public void joinPlan(String faceId, String planId, String date, MyselfPlanBean.DataBean plan) {
        JoinPlanBody joinPlanBody = new JoinPlanBody();
        joinPlanBody.setFaceId(faceId);
        joinPlanBody.setPlanId(planId);
        joinPlanBody.setPlanDate(date);

        model.bindSportPlan(joinPlanBody)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<MyselfPlanBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        joinPlanStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(MyselfPlanBean myselfPlanBean) {
                        if (myselfPlanBean.getCode() == 200) {
                            UserInfoManager.getInstance().setSelfSportPlan(plan);
                            joinPlanStateLiveData.postValueAndSuccess("join");
                        } else {
                            joinPlanStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        joinPlanStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        joinPlanStateLiveData.postIdle();
                    }
                });
    }

    /**
     * 取消计划
     *
     * @param faceId
     * @param planId
     */
    public void unJoinPlan(String faceId, String planId) {
        if (TextUtils.isEmpty(faceId)) {
            faceId = model.getFaceId();
        }

        UnJoinPlanBody unJoinPlanBody = new UnJoinPlanBody();
        unJoinPlanBody.setFaceId(faceId);
        unJoinPlanBody.setPlanId(planId);
        model.unbindSportPlan(unJoinPlanBody)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<MyselfPlanBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        joinPlanStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(MyselfPlanBean myselfPlanBean) {
                        if (myselfPlanBean.getCode() == 200) {
                            UserInfoManager.getInstance().setSelfSportPlan(null);
                            joinPlanStateLiveData.postValueAndSuccess("unjoin");
                        } else {
                            joinPlanStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        joinPlanStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        joinPlanStateLiveData.postIdle();
                    }
                });
    }

    public void setWeek(String faceId, String planId, int week) {
        mWeek.setValue(week);

        initPlanDetails(faceId, planId, weekList.getValue().get(week).getDate());
    }


    public void changeMember(FamilyMembersBean.DataBean.FamilyMembers member) {
        if (member != null && member.getId() != planUserStateLiveData.getValue().getId()) {
            planUserStateLiveData.setValue(member);
        }
    }

    public void hasSelfPlan() {
        model.hasSelfPlan(planUserStateLiveData.getValue().getFaceId())
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<MyselfPlanBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        myselfPlanBeanStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(MyselfPlanBean myselfPlanBean) {
                        if (myselfPlanBean.getCode() == 200) {
                            UserInfoManager.getInstance().setSelfSportPlan(myselfPlanBean.getData());
                            myselfPlanBeanStateLiveData.postValueAndSuccess(myselfPlanBean);
                        } else {
                            myselfPlanBeanStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        myselfPlanBeanStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        myselfPlanBeanStateLiveData.postIdle();
                    }
                });
    }

}
